﻿using System.Collections;
using System.Collections.Generic;
using System.Data;
using AutoMapper;
using System.Linq;
using System;
using ZY.EntityFrameWork.Core.Model.Entity;
using ZY.EntityFrameWork.Core.Model.Dto;
using ZY.EntityFrameWork.Core.Model.Entity.Authority;
using ZY.EntityFrameWork.Core.Model.Dto.Authority;

namespace ZY.EntityFrameWork.Core.DBHelper
{
    /// <summary>
    /// AutoMapper扩展帮助类
    /// </summary>
    public static class AutoMapperHelper
    {
        //初始化，程序初始时调用
        public static void Init()
        {
            Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
        }


        public static T MapTo<T>(this object obj)
        {
            if (obj == null) return default(T);
            Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
            Type t=obj.GetType();
            //类型相同的映射不需要添加映射关系
            if (Mapper.Configuration.FindTypeMapFor(obj.GetType(), typeof(T)) == null)
            {
                if (typeof(T) != obj.GetType())
                {
                    //return default(T);
                }
            }
            return Mapper.Map<T>(obj);
        }

        public class MappingProfile : Profile
        {
            public MappingProfile()
            {
                //TypeMap mapper = Mapper.Configuration.FindTypeMapFor<ArchiveInfo, ArchiveInfoDto>();
                CreateMap<ArchiveInfo, ArchiveInfoDto>().ForMember(dest => dest.GroupNo, ori => ori.MapFrom(s => s.ArvLocation.GroupNo));
                CreateMap<ArvLocation, ArvLocationDto>();
                CreateMap<User, UserDto>().ForMember(dest=>dest.RoleName,ori=>ori.MapFrom(s=>s.UserRole.RoleName));
                CreateMap<Module, ModuleDto>();
                CreateMap<RoleModule, RoleModuleDto>()
                    .ForMember(dest => dest.ModuleName, ori => ori.MapFrom(s => s.Module.ModuleName))
                    .ForMember(dest => dest.RoleName, ori => ori.MapFrom(s => s.Role.RoleName));
                CreateMap<Role, RoleDto>();


                CreateMap<ArchiveInfoDto, ArchiveInfo>();
                CreateMap<ArvLocationDto, ArvLocation>();
                CreateMap<UserDto, User>();
                CreateMap<ModuleDto, Module>();
                CreateMap<RoleModuleDto, RoleModule>();
                CreateMap<RoleDto, Role>();
            }
        }
    }
}